package me.flyray.crm.core.feignserver;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.flyray.common.enums.CustomerType;
import me.flyray.common.exception.BusinessException;
import me.flyray.common.msg.AccountType;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.BizResponseCode;
import me.flyray.common.msg.ResponseCode;
import me.flyray.common.util.EntityUtils;
import me.flyray.common.util.ResponseHelper;
import me.flyray.common.vo.QueryPersonalAccountRequest;
import me.flyray.common.vo.QueryPersonalAccountResponse;
import me.flyray.common.vo.admin.AdminUserRequest;
import me.flyray.common.vo.admin.AdminUserResponse;
import me.flyray.crm.core.biz.customer.CustomerBaseAuthBiz;
import me.flyray.crm.core.biz.customer.CustomerBaseBiz;
import me.flyray.crm.core.biz.personal.PersonalAccountBiz;
import me.flyray.crm.core.biz.personal.PersonalBaseBiz;
import me.flyray.crm.core.biz.personal.PersonalDistributionRelationBiz;
import me.flyray.crm.core.entity.*;
import me.flyray.crm.facade.feignclient.modules.admin.AdminUserServiceClient;
import me.flyray.crm.facade.feignclient.modules.personal.PersonalBaseServiceClient;
import me.flyray.crm.facade.request.DistributionInviteRequest;
import me.flyray.crm.facade.request.PersonalBaseRequest;
import me.flyray.crm.facade.request.RegisterRequest;
import me.flyray.crm.facade.request.personal.Personal3rdAuthRegisterRequest;
import me.flyray.crm.facade.request.personal.PersonalAuthStatusRequest;
import me.flyray.crm.facade.response.personal.PersonalInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: bolei
 * @date: 20:53 2019/2/15
 * @Description: 个人客户
 */

@Api(tags="个人客户")
@Controller
@Slf4j
public class PersonalBaseServiceClientFeign implements PersonalBaseServiceClient {

    @Autowired
    private PersonalBaseBiz personalBaseBiz;
    @Autowired
    private CustomerBaseBiz customerBaseBiz;
    @Autowired
    private CustomerBaseAuthBiz customerBaseAuthBiz;
    @Autowired
    private PersonalAccountBiz personalAccountBiz;
    @Autowired
    private PersonalDistributionRelationBiz personalDistributionRelationBiz;
    @Autowired
    private AdminUserServiceClient adminUserServiceClient;

    /**
     * 根据手机个人客户查询
     * @time 创建时间:2018年9月26日下午4:31:39
     * @param phone
     * @return
     */
    @ResponseBody
    @Override
    public BaseApiResponse<PersonalInfo> queryInfoByPhone(@RequestBody PersonalBaseRequest request){
        log.info("【个人客户查询】   请求参数：{}", EntityUtils.beanToMap(request));
        PersonalBase personalBaseReq = new PersonalBase();
        personalBaseReq.setPlatformId(request.getPlatformId());
        personalBaseReq.setPhone(request.getPhone());
        PersonalBase personalBase = personalBaseBiz.selectOne(personalBaseReq);
        PersonalInfo personalInfo = new PersonalInfo();
        if (null == personalBase) {
            return BaseApiResponse.newSuccess();
        }else{
            BeanUtils.copyProperties(personalBase, personalInfo);
        }
        return BaseApiResponse.newSuccess(personalInfo);
    }

    /**
     * 个人客户查询
     * @author centerroot
     * @time 创建时间:2018年9月26日下午4:31:39
     * @param personalBaseRequest
     * @return
     */
    @ResponseBody
    @Override
    public BaseApiResponse<PersonalInfo> queryInfo(@RequestBody @Valid PersonalBaseRequest personalBaseRequest){
        log.info("【个人客户查询】   请求参数：{}", EntityUtils.beanToMap(personalBaseRequest));
        PersonalBase personalBaseReq = new PersonalBase();
        BeanUtils.copyProperties(personalBaseRequest, personalBaseReq);
        PersonalBase personalBase = personalBaseBiz.selectOne(personalBaseReq);
        PersonalInfo personalInfo = new PersonalInfo();
        if (null == personalBase) {
            throw new BusinessException(BizResponseCode.PER_NOTEXIST);
        }else{
            BeanUtils.copyProperties(personalBase, personalInfo);
        }
        return BaseApiResponse.newSuccess(personalInfo);
    }

    /**
     * @param request
     * @return
     * 分销邀请好友
     * 三级分销一个用户上面最多出现不同级别的三个用户
     */
    @Override
    @ResponseBody
    public BaseApiResponse invite(@RequestBody @Valid DistributionInviteRequest request){

        //将新用户与邀请人关联
        //判断邀请人属于哪级分销
        String inviterPersonalId = request.getInviterPersonalId();
        String inviteePersonalId = request.getInviteePersonalId();
        PersonalBase personalBaseReq = new PersonalBase();
        personalBaseReq.setPersonalId(inviterPersonalId);
        PersonalBase personalBase = personalBaseBiz.selectOne(personalBaseReq);
        if (personalBase == null){
            throw new BusinessException(ResponseCode.USERINFO_NOTEXIST);
        }
        //判断被邀请人是否已经被邀请
        List<PersonalDistributionRelation> customerRelationses = personalDistributionRelationBiz.queryByPersonalId(inviteePersonalId);
        if (customerRelationses != null && customerRelationses.size() > 0){
            return BaseApiResponse.newSuccess();
        }
        PersonalDistributionRelation inviteeCustomer = new PersonalDistributionRelation();
        //根据邀请人的parentID
        List<PersonalDistributionRelation> inviters = personalDistributionRelationBiz.queryByPersonalId(inviterPersonalId);
        if (CollectionUtils.isEmpty(inviters)){
            inviteeCustomer.setFxLevel("1");
        }else {
            PersonalDistributionRelation parent = inviters.get(0);
            inviteeCustomer.setFxLevel(String.valueOf(Integer.valueOf(parent.getFxLevel())+1));
        }
        Date invitedTime = new Date();
        inviteeCustomer.setPlatformId(request.getPlatformId());
        inviteeCustomer.setPersonalId(inviteePersonalId);
        inviteeCustomer.setParentId(inviterPersonalId);
        inviteeCustomer.setParentName(personalBase.getNickname());
        inviteeCustomer.setCreateTime(invitedTime);
        personalDistributionRelationBiz.insert(inviteeCustomer);

        return BaseApiResponse.newSuccess();
    }

    /**
     * @param request
     * @return
     * 分销邀请好友
     * 三级分销一个用户上面最多出现不同级别的三个用户
     */
    @ResponseBody
    public BaseApiResponse nouse_invite(@RequestBody @Valid DistributionInviteRequest request){
        log.info("【三级分销一个用户上面最多出现不同级别的三个用户】   请求参数：{}", EntityUtils.beanToMap(request));
        //将新用户与邀请人关联
        //判断邀请人属于哪级分销
        String inviterPersonalId = request.getInviterPersonalId();
        String inviteePersonalId = request.getInviteePersonalId();
        PersonalBase personalBaseReq = new PersonalBase();
        personalBaseReq.setPersonalId(inviterPersonalId);
        PersonalBase personalBase = personalBaseBiz.selectOne(personalBaseReq);
        if (personalBase == null){
            throw new BusinessException(ResponseCode.USERINFO_NOTEXIST);
        }
        PersonalDistributionRelation isInviteeCustomer = personalDistributionRelationBiz.queryReferrerByPersonalId(inviteePersonalId);
        if (isInviteeCustomer != null){
            return BaseApiResponse.newSuccess();
        }
        List<PersonalDistributionRelation> customerRelationses = personalDistributionRelationBiz.queryByPersonalId(inviterPersonalId);
        int sz = customerRelationses.size();
        Date invitedTime = new Date();
        log.info("邀请关系层级数------{}",sz);
        if (sz == 0) {
            //说明邀请人是顶级分销没有被邀请过的人 受邀人是一级分销
            PersonalDistributionRelation inviteeCustomer = new PersonalDistributionRelation();
            inviteeCustomer.setPlatformId(request.getPlatformId());
            inviteeCustomer.setPersonalId(inviteePersonalId);
            inviteeCustomer.setFxLevel("1");
            inviteeCustomer.setIsReferrer("1");
            inviteeCustomer.setParentId(inviterPersonalId);
            inviteeCustomer.setParentName(personalBase.getNickname());
            inviteeCustomer.setCreateTime(invitedTime);
            personalDistributionRelationBiz.insert(inviteeCustomer);
        }else if(sz == 1) {
            //说明邀请人是第一级分销 受邀人是二级分销需要写两条条记录
            PersonalDistributionRelation invitedCustomer = new PersonalDistributionRelation();
            invitedCustomer.setPlatformId(request.getPlatformId());
            invitedCustomer.setPersonalId(inviteePersonalId);
            invitedCustomer.setFxLevel("1");
            invitedCustomer.setIsReferrer("1");
            invitedCustomer.setParentId(inviterPersonalId);
            invitedCustomer.setParentName(personalBase.getNickname());
            invitedCustomer.setCreateTime(invitedTime);
            personalDistributionRelationBiz.insert(invitedCustomer);
            //受邀人
            PersonalDistributionRelation personalDistributionRelation = customerRelationses.get(0);
            PersonalDistributionRelation ic = new PersonalDistributionRelation();
            ic.setPlatformId(request.getPlatformId());
            ic.setPersonalId(inviteePersonalId);
            ic.setFxLevel("2");
            ic.setIsReferrer("0");
            ic.setParentId(personalDistributionRelation.getParentId());
            ic.setParentName(personalBase.getNickname());
            ic.setCreateTime(invitedTime);
            personalDistributionRelationBiz.insert(ic);
        }else if (sz == 2) {
            //说明邀请人是第二级分销 受邀人是三级分销需要写三条条记录
            PersonalDistributionRelation invitedCustomer = new PersonalDistributionRelation();
            invitedCustomer.setPlatformId(request.getPlatformId());
            invitedCustomer.setPersonalId(inviteePersonalId);
            invitedCustomer.setFxLevel("1");
            invitedCustomer.setIsReferrer("1");
            invitedCustomer.setParentId(inviterPersonalId);
            invitedCustomer.setParentName(personalBase.getNickname());
            invitedCustomer.setCreateTime(invitedTime);
            personalDistributionRelationBiz.insert(invitedCustomer);
            //查询出邀请人的parentId
            for (PersonalDistributionRelation customerRelations : customerRelationses) {
                String parentId = customerRelations.getParentId();
                PersonalBase parent = new PersonalBase();
                parent.setPersonalId(inviterPersonalId);
                parent = personalBaseBiz.selectOne(parent);
                //判断邀请人的上级位于三级分销中第几级
                PersonalDistributionRelation ic = new PersonalDistributionRelation();
                ic.setPlatformId(request.getPlatformId());
                ic.setPersonalId(inviteePersonalId);
                ic.setParentId(parent.getPersonalId());
                ic.setParentName(parent.getNickname());
                ic.setCreateTime(invitedTime);
                if ("1" == customerRelations.getFxLevel()) {
                    ic.setFxLevel("2");
                }else if ("2" == customerRelations.getFxLevel()) {
                    ic.setFxLevel("3");
                }
                invitedCustomer.setIsReferrer("0");
                ic.setParentId(parentId);
                personalDistributionRelationBiz.insert(ic);
            }
        }else if (sz == 3) {
            //说明邀请人是第三级分销 受邀人是邀请人的一级分销需要写一条记录
            PersonalDistributionRelation invitedCustomer = new PersonalDistributionRelation();
            invitedCustomer.setPlatformId(request.getPlatformId());
            invitedCustomer.setPersonalId(inviteePersonalId);
            invitedCustomer.setParentId(inviterPersonalId);
            invitedCustomer.setParentName(personalBase.getNickname());
            invitedCustomer.setCreateTime(invitedTime);
            invitedCustomer.setFxLevel("1");
            invitedCustomer.setIsReferrer("1");
            personalDistributionRelationBiz.insert(invitedCustomer);
        }else if(sz > 3){
            PersonalDistributionRelation invitedCustomer = new PersonalDistributionRelation();
            invitedCustomer.setPlatformId(request.getPlatformId());
            invitedCustomer.setPersonalId(inviteePersonalId);
            invitedCustomer.setParentId(inviterPersonalId);
            invitedCustomer.setParentName(personalBase.getNickname());
            invitedCustomer.setCreateTime(invitedTime);
            invitedCustomer.setFxLevel("9999");
            invitedCustomer.setIsReferrer("1");
            personalDistributionRelationBiz.insert(invitedCustomer);
        }
        return BaseApiResponse.newSuccess();
    }

    /**
     * @param request
     * @return
     * 用户授权状态查询
     * 1:未激活 2:已激活 3:客户信息未补全
     * 查询customer_base_auth表信息查看用户是否授权
     */
    @Override
    @ResponseBody
    public BaseApiResponse<PersonalInfo> queryAuthStatus(@RequestBody @Valid PersonalAuthStatusRequest request){
        log.info("【查询customer_base_auth表信息查看用户是否授权】   请求参数：{}", EntityUtils.beanToMap(request));
        CustomerBaseAuth customerBaseAuth = new CustomerBaseAuth();
        customerBaseAuth.setAuthMethod(request.getThirdCode());
        customerBaseAuth.setCredential(request.getXId());
        customerBaseAuth.setCustomerId(request.getPersonalId());
        customerBaseAuth = customerBaseAuthBiz.selectOne(customerBaseAuth);
        PersonalInfo personalInfo = new PersonalInfo();
        if (customerBaseAuth == null){
            personalInfo.setStatus("1");
            return BaseApiResponse.newSuccess(personalInfo);
        }
        //查询用户信息是否补全
        PersonalBase personalBase = new PersonalBase();
        personalBase.setPlatformId(customerBaseAuth.getPlatformId());
        personalBase.setPersonalId(customerBaseAuth.getCustomerId());
        personalBase = personalBaseBiz.selectOne(personalBase);
        if (personalBase == null ){
            personalInfo.setStatus("3");
            return BaseApiResponse.newSuccess(personalInfo);
        }
        if (StringUtils.isEmpty(personalBase.getRealName())){
            personalInfo.setStatus("3");
        }else {
            personalInfo.setStatus("2");
        }
        //查询用户的余额信息
        PersonalAccount personalAccount = new PersonalAccount();
        personalAccount.setPersonalId(personalBase.getPersonalId());
        personalAccount.setAccountType(AccountType.ACC_INTEGRAL.getCode());
        //Fixme
        //todo 查询总账
        QueryPersonalAccountRequest request1 = new QueryPersonalAccountRequest();
        request1.setPersonalId(personalBase.getPersonalId());
        request1.setPlatformId(request.getPlatformId());
        QueryPersonalAccountResponse response = personalAccountBiz.queryPersonalAcount(request1);
        //personalAccount = personalAccountBiz.selectOne(personalAccount);
        if (response == null){
            personalInfo.setBalance("0");
        }else {
            personalInfo.setBalance(String.valueOf(response.getTotalPoint()));
        }
        List<PersonalDistributionRelation> personalDistributionRelations = personalDistributionRelationBiz.queryByPersonalId(personalBase.getPersonalId());
        if (CollectionUtils.isEmpty(personalDistributionRelations)){
            personalInfo.setPersonalLevel(-1);
        }else {
            personalInfo.setPersonalLevel(Integer.valueOf(personalDistributionRelations.get(0).getFxLevel()));
        }
        //客户经理标识 1 是 0 否
        AdminUserRequest adminUserRequest = new AdminUserRequest();
        adminUserRequest.setUserId(personalBase.getPersonalId());
        BaseApiResponse<List<AdminUserResponse>> listBaseApiResponse  = adminUserServiceClient.getUserList(adminUserRequest);
        if (listBaseApiResponse.getSuccess() && listBaseApiResponse.getData().size()>0){
            personalInfo.setPersonalType("1");
        }else {
            personalInfo.setPersonalType("0");
        }
        personalInfo.setCustomerId(personalBase.getCustomerId());
        personalInfo.setPersonalId(personalBase.getPersonalId());
        return BaseApiResponse.newSuccess(personalInfo);
    }

    /**
     * @param request
     * @return
     * 第三方授权授权,及基础信息授权注册
     * 将用户信息写入customer_base和customer_base_auth及personal_base
     */
    @Override
    @ResponseBody
    public BaseApiResponse personal3rdAuthRegister(@RequestBody @Valid Personal3rdAuthRegisterRequest request){
        log.info("第三方授权授权,及基础信息授权注册   请求参数：{}", EntityUtils.beanToMap(request));
        RegisterRequest registerRequest = new RegisterRequest();
        BeanUtils.copyProperties(request,registerRequest);
        registerRequest.setCustomerType(CustomerType.CUST_PERSONAL.getCode());
        registerRequest.setPassword("123456");
        //根据手机号查询用户是否存在 存在则激活 不存在在注册
        PersonalBase personalBaseReq = new PersonalBase();
        personalBaseReq.setPlatformId(request.getPlatformId());
        personalBaseReq.setPhone(request.getPhone());
        CustomerBaseAuth customerBaseAuth = new CustomerBaseAuth();
        PersonalBase personalBase = personalBaseBiz.selectOne(personalBaseReq);
        if (personalBase == null){
            registerRequest.setAuthenticationStatus("02");
            registerRequest.setPersonalLevel("V0");
            CustomerBase customerBase = customerBaseBiz.register(registerRequest);
            customerBaseAuth.setCustomerId(customerBase.getPersonalId());
            customerBaseAuth.setPlatformId(request.getPlatformId());
            customerBaseAuth.setAuthMethod(request.getThirdCode());
            customerBaseAuth.setCredential(request.getXId());
            customerBaseAuth.setIdentifier(request.getNickname());
            customerBaseAuth.setCustomerType(CustomerType.CUST_PERSONAL.getCode());
            customerBaseAuthBiz.insert(customerBaseAuth);

        }else if (!"02".equals(personalBase.getAuthenticationStatus())){
            customerBaseAuth.setCustomerId(personalBase.getPersonalId());
            personalBase.setAuthenticationStatus("02");
            personalBaseBiz.updateSelectiveById(personalBase);
            customerBaseAuth.setCustomerId(personalBase.getPersonalId());
            customerBaseAuth.setPlatformId(request.getPlatformId());
            customerBaseAuth.setAuthMethod(request.getThirdCode());
            customerBaseAuth.setCredential(request.getXId());
            customerBaseAuth.setIdentifier(request.getNickname());
            customerBaseAuth.setCustomerType(CustomerType.CUST_PERSONAL.getCode());
            customerBaseAuthBiz.insert(customerBaseAuth);
        }

        return BaseApiResponse.newSuccess();
    }

    /**
     * @param request
     * @return
     * 更新用户信息
     */
    @Override
    @ResponseBody
    public BaseApiResponse updatePersonalInfo(@RequestBody PersonalBaseRequest request){
        personalBaseBiz.updateObj(request);
        return BaseApiResponse.newSuccess();
    }

}
